<?php
session_start();
require_once __DIR__.'/../../utils/checkTokenUtils.php';
require_once __DIR__.'/../../utils/MysqlDBUtils.php';
use utils\MysqlDBUtils;

// 仅允许POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die("错误：仅支持POST请求");
}

// 初始化数据库连接
$dbUtil = new MysqlDBUtils();

// 获取并验证表单数据
$title = isset($_POST['title']) ? trim($_POST['title']) : '';
$author = isset($_POST['author']) ? trim($_POST['author']) : '';
$isbn = isset($_POST['isbn']) ? trim($_POST['isbn']) : '';
$publisher = isset($_POST['publisher']) ? trim($_POST['publisher']) : '';
$publish_date = isset($_POST['publish_date']) ? trim($_POST['publish_date']) : '';
$price = isset($_POST['price']) ? trim($_POST['price']) : '';
$stock = isset($_POST['stock']) ? intval($_POST['stock']) : 0;
$categoryId = isset($_POST['category_id'])? intval($_POST['category_id']) : 0;

// 验证必填字段
if (empty($title) || empty($author) || empty($isbn)) {
    $_SESSION['error_message'] = '错误：必填字段（书名、作者、ISBN）不能为空';
    header("Location: Books.php");
    exit;
}

// 转义特殊字符防止SQL注入
$escapedTitle = $dbUtil->escapeString($title);
$escapedAuthor = $dbUtil->escapeString($author);
$escapedIsbn = $dbUtil->escapeString($isbn);
$escapedPublisher = $dbUtil->escapeString($publisher);
$escapedPublishDate = $dbUtil->escapeString($publish_date);
$escapedPrice = $dbUtil->escapeString($price);
$escapedCategoryId = $dbUtil->escapeString($categoryId);

// 构建插入SQL
$insertSql = "INSERT INTO book (title, author, isbn, publisher, publish_date, price, stock,category_id) 
              VALUES ('$escapedTitle', '$escapedAuthor', '$escapedIsbn', '$escapedPublisher', '$escapedPublishDate', '$escapedPrice', $stock,$categoryId)";

// 执行插入
$result = $dbUtil->prepareQuery($insertSql);

if ($result !== false) {
    $_SESSION['success_message'] = '图书添加成功！';
} else {
    $_SESSION['error_message'] = '错误：数据库插入失败';
}

// 重定向回图书列表
header("Location: Books.php");
exit;